package com.chuji.crmcj.act;

import android.app.AlertDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.RecToolsAdp;
import com.chuji.crmcj.bean.InsRecInfo;
import com.chuji.crmcj.bean.LoanRecInfo;
import com.chuji.crmcj.bean.ReceptionInfo;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by w.pitt on 2016/1/12.
 */
public class ReceptionActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private RelativeLayout mRlNotCon;
    private GridView mGvTools;
    private TextView mTv_loan;
    private TextView mTv_loan_date;
    private TextView mTv_loan_money;
    private TextView mTv_loan_interest;
    private TextView mTv_loan_year_limt;
    private TextView mTv_totle_cost;
    private TextView mTv_repay_month;
    private TextView mTv_additional_cost;
    private TextView mTv_insurance;
    private TextView mTv_insurance_date;
    private TextView mTv_car_cost;
    private TextView mTv_insurance_money;
    private TextView mTv_compulsory_insurance;
    private TextView mTv_theft_insurance;
    private TextView mTv_responsibility_insurance;
    private TextView mTv_scratch_insurance;
    private TextView mTv_car_loss_insurance;
    private TextView mTv_personnel_insurance;
    private TextView mTv_third_party;
    private TextView mTv_autoignition_insurance;
    private TextView mTv_wading_insurance;
    private TextView mTv_glass_fracture;
    private TextView mTv_not_;
    private ImageView mSetting;
    private String flowID;
    /*关联成功*/
    private LinearLayout mLlConnSucc;
    private TextView mTvCusNum;
    private TextView mTvEnterTime;
    private TextView mTvName;
    private TextView mTvWantCar;
    private TextView mTvTelNumber;
    private TextView mEnterTime;
    private PopupWindow popupWindow;
    private RelativeLayout mRlLoan;
    private RelativeLayout mRlInsure;
    private TextView mTvCount;
    private String userID;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_reception);
        mTvCount = (TextView) findViewById(R.id.tv_count);
        mTvCusNum = (TextView) findViewById(R.id.tv_people_number);
        mRlLoan = (RelativeLayout) findViewById(R.id.rl_loan);
        mRlInsure = (RelativeLayout) findViewById(R.id.rl_insure);
        mLlConnSucc = (LinearLayout) findViewById(R.id.ll_conn_succ);
        mSetting = (ImageView) findViewById(R.id.setting);
        mRlNotCon = (RelativeLayout) findViewById(R.id.rl_not_con);
        mGvTools = (GridView) findViewById(R.id.gv_tools);
        mTv_loan = (TextView) findViewById(R.id.tv_loan);
        mTv_loan_date = (TextView) findViewById(R.id.tv_loan_date);
        mTv_loan_money = (TextView) findViewById(R.id.tv_loan_money);
        mTv_loan_interest = (TextView) findViewById(R.id.tv_loan_lixi);
        mTv_loan_year_limt = (TextView) findViewById(R.id.tv_loan_year_limt);
        mTv_totle_cost = (TextView) findViewById(R.id.tv_totle_cost);
        mTv_repay_month = (TextView) findViewById(R.id.tv_repay_month);
        mTv_additional_cost = (TextView) findViewById(R.id.tv_additional_cost);
        mTv_insurance = (TextView) findViewById(R.id.tv_insurance);
        mTv_insurance_date = (TextView) findViewById(R.id.tv_insurance_date);
        mTv_car_cost = (TextView) findViewById(R.id.tv_car_cost);
        mTv_insurance_money = (TextView) findViewById(R.id.tv_insurance_money);
        mTv_compulsory_insurance = (TextView) findViewById(R.id.tv_compulsory_insurance);
        mTv_theft_insurance = (TextView) findViewById(R.id.tv_theft_insurance);
        mTv_responsibility_insurance = (TextView) findViewById(R.id.tv_responsibility_insurance);
        mTv_scratch_insurance = (TextView) findViewById(R.id.tv_scratch_insurance);
        mTv_car_loss_insurance = (TextView) findViewById(R.id.tv_car_loss_insurance);
        mTv_personnel_insurance = (TextView) findViewById(R.id.tv_personnel_insurance);
        mTv_third_party = (TextView) findViewById(R.id.tv_third_party);
        mTv_autoignition_insurance = (TextView) findViewById(R.id.tv_autoignition_insurance);
        mTv_wading_insurance = (TextView) findViewById(R.id.tv_wading_insurance);
        mTv_glass_fracture = (TextView) findViewById(R.id.tv_glass_fracture);
        mTv_not_ = (TextView) findViewById(R.id.tv_not_calculation);
        mTvEnterTime = (TextView) findViewById(R.id.tv_time);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvWantCar = (TextView) findViewById(R.id.tv_want_car);
        mTvTelNumber = (TextView) findViewById(R.id.tv_number);
        mEnterTime = (TextView) findViewById(R.id.tv_enter_time);
    }

    @Override
    protected void initData() {
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        RecToolsAdp adapter = new RecToolsAdp();
        mGvTools.setAdapter(adapter);
        mTvBarTitle.setText("新的接待");
    }

    @Override
    protected void onStart() {
        super.onStart();
        //网络请求
        requestNetData();

        String customerID = SPUtils.getString(UIUtils.getContext(), "CustomerID", "");
        if (!TextUtils.isEmpty(customerID)) {
            mRlNotCon.setVisibility(View.GONE);
            mLlConnSucc.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isCountShow) {
            mTvCount.setVisibility(View.GONE);
        }
    }

    private void requestNetData() {
        //获取来访客户
        reqComeStore();

        flowID = SPUtils.getString(UIUtils.getContext(), "FlowID", "");
        if (!TextUtils.isEmpty(flowID) && !flowID.equals("")) {
            //获取保险记录
            reqLoanRecInfo();
            //获取保险记录信息
            reqInsRecInfo();
        }
    }

    private void reqComeStore() {
        String strURL = String.format(UrlUtils.GetCurrentPassengerInfo + "&SalesID=%s", userID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final ReceptionInfo receptionInfo = JSON.parseObject(s, ReceptionInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (receptionInfo.isSuccess() && receptionInfo.getApiParamObj().size() != 0) {
                            mTvCusNum.setText(receptionInfo.getApiParamObj().get(0).getCustomerCount() + "人");
                            mTvEnterTime.setText(receptionInfo.getApiParamObj().get(0).getEnterTime());
                            String flowID = receptionInfo.getApiParamObj().get(0).getFlowID();

                            SPUtils.saveString(UIUtils.getContext(), "FlowID", flowID);

                            mTvName.setText(receptionInfo.getApiParamObj().get(0).getName());
                            mTvWantCar.setText(receptionInfo.getApiParamObj().get(0).getCarModel());
//                            String tel = receptionInfo.getApiParamObj().get(0).getTel().toString();
//                            if (tel.length() == 11) {
                            mTvTelNumber.setText(receptionInfo.getApiParamObj().get(0).getTel());
//                            } else {
//                                mTvTelNumber.setText(tel);
//                            }
                            mEnterTime.setText(receptionInfo.getApiParamObj().get(0).getEnterTime());
                        } else {
                            UIUtils.showToastSafe("新的接待   。test试用");
                        }
                    }
                });
            }
        });
    }

    private Boolean isCountShow = false;

    private void reqInsRecInfo() {
        String strURL = String.format(UrlUtils.GETINSRECINFO + "&FlowID=%s", flowID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final InsRecInfo insRecInfo = JSON.parseObject(s, InsRecInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (insRecInfo.getApiParamObj().size() != 0) {
                            isCountShow = true;
                            mRlInsure.setVisibility(View.VISIBLE);
                            mTv_car_cost.setText(insRecInfo.getApiParamObj().get(0).getCarAmount());
                            mTv_insurance_date.setText(insRecInfo.getApiParamObj().get(0).getCreateTime());
                            //TODO 数据不够

                        }
                    }
                });
            }
        });
    }

    private void reqLoanRecInfo() {
        String strURL = String.format(UrlUtils.GETLOANRECINFO + "&FlowID=%s", flowID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final LoanRecInfo loanRecInfo = JSON.parseObject(s, LoanRecInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loanRecInfo.getApiParamObj().size() != 0) {
                            isCountShow = true;
                            mRlLoan.setVisibility(View.VISIBLE);
                            mTv_loan_money.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getAmount()));
                            mTv_loan_interest.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getRate()));
                            mTv_loan_year_limt.setText(loanRecInfo.getApiParamObj().get(0).getYears());
                            mTv_totle_cost.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getTotalAmount()));
                            mTv_repay_month.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getMonthAmount()));
                            mTv_loan_date.setText(loanRecInfo.getApiParamObj().get(0).getCreateTime());
                            mTv_additional_cost.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getAmount() - loanRecInfo.getApiParamObj().get(0).getTotalAmount()));
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void initListener() {
        mBtnBarLeftArr.setOnClickListener(this);
        mGvTools.setOnItemClickListener(this);
        mSetting.setOnClickListener(this);
        mRlNotCon.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_left_arr:
                finish();
                break;
            case R.id.rl_not_con:
                startDataComplete();
                break;
            case R.id.ll_conn_succ:
                startDataComplete();
                break;
            case R.id.setting:
                showPopupWindow(mSetting);
                break;
            //查询自己   传递参数
            case R.id.tv_search_myself:
                popupWindow.dismiss();
                Intent secSelf = new Intent(UIUtils.getContext(), SearchActivity.class);
                secSelf.putExtra("Lable", ConstantValue.SEARCHSELF);
                UIUtils.startActivity(secSelf);
                break;
            //查询别人   传递参数
            case R.id.tv_search_other:
                popupWindow.dismiss();
                Intent secOther = new Intent(UIUtils.getContext(), SearchActivity.class);
                secOther.putExtra("Lable", ConstantValue.SEARCHOTHER);
                UIUtils.startActivity(secOther);
                break;
            case R.id.tv_cus_leave:
                popupWindow.dismiss();
                showLeaveDialog();
                break;
        }
    }

    private void startDataComplete() {
        Intent mIntent = new Intent(this, DataCompleteActivity.class);
        mIntent.putExtra("FlowID", flowID);
        UIUtils.startActivity(mIntent);
    }

    private AlertDialog leaveDialog;

    private void showLeaveDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        leaveDialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_cus_leave, null);// 给dialog设定特定布局
        // dialog.setView(view);
        leaveDialog.setView(view, 0, 0, 0, 0); //去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqLeaveNet();
                leaveDialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leaveDialog.dismiss();
            }
        });
        leaveDialog.show();
    }

    private void reqLeaveNet() {
//        String strURL = String.format(UrlUtils.PASSAGEFLOWEXIT + "&FlowID=%s&SalesID=%s", flowID, salerID);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("离店申请成功！");
//                    }
//                });
//            }
//        });

        String strURL = String.format(UrlUtils.PASSAGEFLOWEXIT + "&FlowID=%s&SalesID=%s", flowID, userID);
        Map<String, String> map = new HashMap<String, String>();
        map.put("FlowID", flowID);
        map.put("SalesID", userID);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("离店申请已处理");
                //将sp中customerID 制空
                SPUtils.saveString(UIUtils.getContext(), "CustomerID", "");
                SPUtils.saveString(UIUtils.getContext(), "FlowID", "");
                SPUtils.saveInt(UIUtils.getContext(), "Free", 1);
                //通知 应该重新刷新
                UIUtils.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            }
        });
    }

    protected void showPopupWindow(View view) {
        // TextView contentView = new TextView(this);
        // contentView.setBackgroundColor(Color.RED);
        View contentView = View.inflate(this, R.layout.item_popup_window, null);
        TextView mSearchSelf = (TextView) contentView.findViewById(R.id.tv_search_myself);
        TextView mSearchOther = (TextView) contentView.findViewById(R.id.tv_search_other);
        TextView mCusLeave = (TextView) contentView.findViewById(R.id.tv_cus_leave);

        mSearchSelf.setOnClickListener(this);
        mSearchOther.setOnClickListener(this);
        mCusLeave.setOnClickListener(this);
        // 初始化气泡控件
        // 第一个参数:需要展示的view
        popupWindow = new PopupWindow(contentView, RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        // side旁边 点击旁边让小气泡消失
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        // //设置小气泡的背景。是一个透明色
        popupWindow.setBackgroundDrawable(UIUtils.getDrawable(R.drawable.transparent));
        popupWindow.showAsDropDown(view, UIUtils.dip2px(-100), UIUtils.dip2px(17));
        //设置动画
//        popupWindow.setAnimationStyle(R.style.PopupAnimationDialog);
        // 第一个参数：展示 在某某控件的下方
        // 第二个参数：表示x轴的偏移量
        // 第三个参数：表示y轴的偏移量
//        popupWindow.showAsDropDown(view, 80, -view.getHeight());
        // 展示在某某位置
//         popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, 100,
//         100);
//		int[] arrayOfInt = new int[2];
//		view.getLocationInWindow(arrayOfInt);
//		popupWindow.showAtLocation(view, 51, 60 + arrayOfInt[0], arrayOfInt[1]);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            case 0:
                UIUtils.startActivity(new Intent(this, LendCounterActivity.class));
                break;
            case 1:
                UIUtils.startActivity(new Intent(this, InsureCalAct.class));
                break;
            case 2:
                UIUtils.startActivity(new Intent(this, CarTypeStockActivity.class));
                break;
        }
    }
}
